package com.tjsiqi.service;

import com.alibaba.druid.support.json.JSONUtils;
import com.google.common.base.Preconditions;
import com.tjsiqi.beans.PageQuery;
import com.tjsiqi.beans.PageResult;
import com.tjsiqi.common.JsonData;
import com.tjsiqi.common.RequestHolder;
import com.tjsiqi.dao.SysUserMapper;
import com.tjsiqi.exception.ParamException;
import com.tjsiqi.model.SysUser;
import com.tjsiqi.param.SearchUserNameParam;
import com.tjsiqi.param.SearchUserParam;
import com.tjsiqi.param.SearchstRwdParam;
import com.tjsiqi.param.UserParam;
import com.tjsiqi.util.BeanValidator;
import com.tjsiqi.util.IpUtil;
import com.tjsiqi.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysLogService sysLogService;

    //加载新注册用户数
    public  int getNewUserCount() {
        int newUserCount;
        newUserCount = sysUserMapper.getNewUserCount(0);
        return newUserCount;
    }
// 保存用户
    public int save(UserParam param) {
        BeanValidator.check(param);
        if(checkTelephoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用");
        }
        if(checkEmailExist(param.getMail(), param.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        String password = param.getPassword();
        //TODO:
//        password = "12345678";
        String encryptedPassword = MD5Util.encrypt(password);
        SysUser user = SysUser.builder().username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .password(encryptedPassword).deptId(param.getDeptId()).registerTime(param.getRegisterTime()).status(param.getStatus()).jbzName(param.getJbzName()).jbzCode(param.getJbzCode()).remark(param.getRemark()).build();
        if (RequestHolder.getCurrentUser() != null && RequestHolder.getCurrentRequest() != null) {
            user.setOperator(RequestHolder.getCurrentUser().getUsername());
            user.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        } else {
            user.setOperator("RegisterPage");
            user.setOperateIp("127.0.0.1");
        }
        user.setOperateTime(new Date());

        // TODO: sendEmail

        int sysUserId = sysUserMapper.insertSelective(user);
        sysLogService.saveUserLog(null, user);
        return sysUserId;
    }
//  保存用户
    public void saveUser(SysUser param) {
//        BeanValidator.check(param);
//        if(checkTelephoneExist(param.getTelephone(), param.getId())) {
//            throw new ParamException("电话已被占用");
//        }
//        if(checkEmailExist(param.getMail(), param.getId())) {
//            throw new ParamException("邮箱已被占用");
//        }
        String password = param.getPassword();
        //TODO:
//        password = "12345678";
        String encryptedPassword = MD5Util.encrypt(password);
        SysUser user = SysUser.builder().username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .password(encryptedPassword).deptId(param.getDeptId()).status(param.getStatus()).jbzCode(param.getJbzCode()).remark(param.getRemark()).jbzCode(param.getJbzCode()).build();
//        user.setOperator(RequestHolder.getCurrentUser().getUsername());
//        user.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        user.setOperateTime(new Date());

        // TODO: sendEmail

        sysUserMapper.insertSelective(user);
//        sysLogService.saveUserLog(null, user);
    }
    // 更新用户
    public void update(UserParam param) {
        BeanValidator.check(param);
        if(checkTelephoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用");
        }
        if(checkEmailExist(param.getMail(), param.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before, "待更新的用户不存在");
        SysUser after = SysUser.builder().id(param.getId()).username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .deptId(param.getDeptId()).status(param.getStatus()).jbzName(param.getJbzName()).jbzCode(param.getJbzCode()).registerTime(param.getRegisterTime()).remark(param.getRemark()).build();
        if(param.getPassword() != null && param.getPassword() !=""){
            after.setPassword(MD5Util.encrypt(param.getPassword()));
        }
        if(RequestHolder.getCurrentUser() != null  && RequestHolder.getCurrentRequest() != null) {
            after.setOperator(RequestHolder.getCurrentUser().getUsername());
            after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        }else{
            after.setOperator("RegisterPage");
            after.setOperateIp("127.0.0.1");
        }
        after.setOperateTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveUserLog(before, after);
    }

    public void updateById(SysUser param) {
        if(checkTelephoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用");
        }
        if(checkEmailExist(param.getMail(), param.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before, "待更新的用户不存在");
        if(param.getPassword() != null && param.getPassword() !=""){
            param.setPassword(MD5Util.encrypt(param.getPassword()));
        }
        param.setOperateTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(param);
//        sysLogService.saveUserLog(before, after);
    }

    public boolean checkEmailExist(String mail, Integer userId) {
        return sysUserMapper.countByMail(mail, userId) > 0;
    }

    public boolean checkTelephoneExist(String telephone, Integer userId) {
        return sysUserMapper.countByTelephone(telephone, userId) > 0;
    }

    public SysUser findByKeyword(String keyword) {
        return sysUserMapper.findByKeyword(keyword);
    }

    public PageResult<SysUser> getPageByDeptId(int deptId, PageQuery page) {
        BeanValidator.check(page);
        int count = sysUserMapper.countByDeptId(deptId);
        System.out.println("返回的count"+count);
        if (count > 0) {
            List<SysUser> list = sysUserMapper.getPageByDeptId(deptId, page);
//            System.out.println("查看返回结果"+JSONUtils.toJSONString(list));
            System.out.println("------123");
            for ( SysUser sysUser :list){
                System.out.println("-----sysuser"+sysUser);
            }
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        System.out.println("------456");
        return PageResult.<SysUser>builder().build();
    }

    public List<SysUser> getAll() {
        return sysUserMapper.getAll();
    }

    public PageResult<SysUser> getPageByname(SearchUserParam searchUserParam, PageQuery page) {
        BeanValidator.check(page);
        if (StringUtils.isNotBlank(searchUserParam.getJbzName())) {
           String  jbzname = "%" + searchUserParam.getJbzName() + "%";
           searchUserParam.setJbzName(jbzname);
        }else{
            searchUserParam.setJbzName(null);
        }
        int count = sysUserMapper.countByname(searchUserParam);
        if (count > 0) {
            List<SysUser> list = sysUserMapper.getPageByname(searchUserParam, page);
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        return PageResult.<SysUser>builder().build();
    }
    //  查询用户
    public PageResult<SysUser> getPageByUsername(SearchUserNameParam searchUserNameParam, PageQuery page) {
        BeanValidator.check(page);
        if (StringUtils.isNotBlank(searchUserNameParam.getUsername())) {
            String  username = "%" + searchUserNameParam.getUsername() + "%";
            searchUserNameParam.setUsername(username);
        }else{
            searchUserNameParam.setUsername(null);
        }
        int count = sysUserMapper.countByUsername(searchUserNameParam);
        if (count > 0) {
            List<SysUser> list = sysUserMapper.getPageByUsername(searchUserNameParam, page);
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    public boolean checkPhoneNum(String phoneNum) {
        return sysUserMapper.checkPhoneNum(phoneNum) > 0;
    }

    public boolean checkMail(String mail) {
        return sysUserMapper.checkMail(mail) > 0;
    }

    public boolean checkjbzCode(String jbzCode) {
        return sysUserMapper.checkjbzCode(jbzCode) > 0;
    }

    public SysUser getUserInfo(String jbzCode, int userId) {
        SysUser sysUser = sysUserMapper.getUserInfo(jbzCode,userId);
        return sysUser;
    }
}
